<?php

/*
   EJEMPLO DE USO:
   $email = new CakeEmail();
   $email->transport('DB');
   $email->from(array('me@example.com' => 'My Site'));
   $email->to('you@example.com');
   $email->subject('About');
   $email->send('My message');
 */

App::uses('AbstractTransport', 'Network/Email');

class DBTransport extends AbstractTransport {

    public function send(CakeEmail $email) {
        global $MODEL;
        
        $data = array(
            "fecha_carga" => date("Y-m-d H:i:s"),
            "fecha_envio" => date("Y-m-d H:i:s"),
            "server_id" => $this->getServer(),
            "html" => "SI",
            "destino" => $this->obtenerDestinatarios($email->to()),
            "asunto" => $email->subject(),
            "cuerpo" => reset($email->message()),
            "adjuntos" => implode(",", $email->attachments()),
            "cabeceras" => $this->obtenerCabeceras($email->getHeaders()),
            "charset" => $email->charset,
            "estado" => "SIN ENVIAR",
            "intentos" => 0
        );

        $MODEL->Query("INSERT INTO msg_mensajes (" . implode(",", array_keys($data)) . ") VALUES ('" . implode("','", $data) . "')");
    }

    private function obtenerDestinatarios($to) {
        $str = "";
        foreach ($to as $key => $value) {
            $str.= $value . ($key != $value ? ' <' . $key . '>' : '') . ',';
        }
        return substr($str, 0, strlen($str)-1);
    }
    
    private function obtenerCabeceras($headers) {
        $str = "";
        foreach ($headers as $key => $value) {
            $str.= $key . " => " . $value . '|';
        }
        return substr($str, 0, strlen($str)-1);
    }
    
    private function getServer() {
        global $MODEL;
        $sqlarray = $MODEL->query("SELECT * FROM configurations LIMIT 1");

        if (isset($sqlarray[0]['configurations']['server_emails'])) {
            return $sqlarray[0]['configurations']['server_emails'];
        }
        return 0;
    }

}